<template>
  <div>
    <!-- 操作区 -->
    <div class="editor-bar" ref="editorBar">
      <div class="file-icon">
        <img @click='$refs.inputFile.click()'
          src="https://blog-huahua.oss-cn-beijing.aliyuncs.com/blog/code/file_icon.png" alt="">
        <input ref="inputFile" hidden type="file" @click='$event.target.value = null' @change='uploadFile'>
      </div>
    </div>
    <div class="editor-text-wrap">
      <div class="editor-text" ref="editorText"></div>
    </div>
    <!-- 附件区 -->
    <ul class="file-list" v-if="editorFiles.length">
      <li class="file-item" v-for="item, i in editorFiles" :key="i" is='file-item' :file='item' @delFile='delFile'>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'
import E from "wangeditor";
import FileItem from "./FileItem";
export default {
  name: "editor",
  components: { FileItem },
  props: {
    // 增加content，有内容的时候直接传进来
    content: {
      type: String,
      default() {
        return "";
      }
    },
    // files，在有附件的时候可以传过来
    files: {
      type: Array,
      default() {
        return [];
      }
    },
    uploadImgUrl: {
      type: String,
      default() {
        return '';
      }
    },
    uploadFileUrl: {
      type: String,
      default() {
        return '';
      }
    },
    deleteFileUrl: {
      type: String,
      default() {
        return '';
      }
    },
  },
  data() {
    return {
      // 富文本内容
      editorContent: "",
      // 附件
      editorFiles: []
    };
  },
  // 这里直接监控同步数据，当然也可以用store
  watch: {
    editorContent(newValue) {
      this.$emit("update:content", newValue);
    },
    editorFiles(newValue) {
      this.$emit("update:files", newValue);
    }
  },
  mounted() {
    // 将content赋值，editorContent变化的时候，不改变父组件的content
    this.editorContent = this.content;
    // 拷贝，注意设置上传状态 name: file.name, size: file.size, isUploaded: false, url: ""
    let files = [...this.files];
    files.length && files.forEach(item => (item.isUploaded = true));
    this.editorFiles = [...files];
    // 创建编辑器
    this.createEditor();
    // 设置内容
    this._setInitContent(this.editorContent);
  },
  methods: {
    clear() {
      this.editor.txt.clear()
    },
    async uploadFile(e) {
      let files = e.target.files;
      for (let i = 0; i < files.length; i++) {
        await this._handleSingleFile(files[i]);
      }
    },
    async _handleSingleFile(file) {
      // 存一份 name是下载的时候显示的名字 size一样 isUploaded是不是上传完
      this.curFile = {
        name: file.name,
        size: file.size,
        isUploaded: false,
        url: ""
      };
      let userData = JSON.parse(sessionStorage.getItem('logOnUser'))
      // 上传,上传成功之后设置状态和下载地址
      let formData = new FormData()
      formData.append('files', file)
      axios({
        method: 'post',
        url: defaultUrl+this.uploadFileUrl, //此处为往后台发送请求的地址
        data: formData,
        headers: {
          account: userData.account,
          token: userData.token,
        },
        timeout: 20000,
      }).then(res => {
        console.log(res, '上传结果');
        if (res.data.code == 200) {
          this.curFile.isUploaded = true;
          this.curFile.url = res.data.data[0];
          this.editorFiles.push(this.curFile);
          this.$emit('getFile', this.editorFiles)
        } else {
          this.$message.error(res.data.message)
        }
      });

    },
    // 删除文件的时候
    delFile(val) {
      // this.editorFiles.splice(index, 1);

      this.editorFiles.forEach((el, i) => {
        if (el.url == val.url) {
          this.$emit('DeleteFile', this.editorFiles[i])
          this.editorFiles.splice(i, 1)
          this.$emit('getFile', this.editorFiles)
        }
      })
      // let params = {
      //   "filename": val.url
      // }
      // axios({
      //   method: 'post',
      //   url: this.deleteFileUrl, //此处为往后台发送请求的地址
      //   data: params,
      //   timeout: 20000,
      // }).then(res => {
      //   if (res.data.code == 200) {
      //     this.editorFiles.forEach((el, i) => {
      //       if (el.url == val.url) {
      //         this.editorFiles.splice(i, 1)
      //       }
      //     })
      //     this.$emit('getFile', this.editorFiles)
      //   }
      // });
    },
    // 配置参数 创建编辑器
    createEditor() {
      // 初始化容器
      let editor = new E(this.$refs.editorBar, this.$refs.editorText);
      // 方便将配置拆开写
      this.editor = editor;
      // 将富文本的html的内容变化时赋值同步到editorContent，这里的change事件将值赋值给editorContent
      this._syncContent();
      // 设置上传本地图片
      this._setUploadLocalImg();
      console.log(editor.config, '所有');
      editor.config.colors = [
        '#000000',
        '#ffffff',
        '#aaaaaa',
        '#89e1f9',
        '#1890ff',
        '#2932e1',
        '#e10602',
        '#ffff00',
        '#abff22',
        '#20820f',
        '#fe91b4',
        '#894924',
        '#7b007b',
        '#4d007b',
        '#ff4a01',
      ]
      editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        // 'link',
        'list',
        // 'todo',
        'justify',
        // 'quote',
        // 'emoticon',
        // 'table',
        // 'code',

        'splitLine',
        'image',
        // 'undo',
        // 'redo',

      ]
      // 创建编辑器
      editor.create();
    },
    _syncContent() {
      // 设置在create之前，当内容变化的时候，同步editorContent
      this.editor.config.onchange = html => {
        this.editorContent = html;
      };
    },
    _setInitContent(content) {
      this.editor.txt.html(content);
    },
    // 上传图片
    _setUploadLocalImg() {
      // 自定义上传图片
      this.editor.config.customUploadImg = async (files, insert) => {
        // files 是 input 中选中的文件列表，遍历上传
        for (let i = 0; i < files.length; i++) {
          let file = files[i];
          let formData = new FormData()
          formData.append('pics', file)// 传文件
          formData.append('id', 6)
          let userData = JSON.parse(sessionStorage.getItem('logOnUser'))
          axios({
            method: 'post',
            url:defaultUrl+ this.uploadImgUrl,
            data: formData,
            headers: {
              account: userData.account,
              token: userData.token,
            },
            timeout: 20000,
          }).then(res => {
            // insert是嵌入到内容里面的方法
            insert(res.data.data[0]);
          });
        }
      };
    },

  }
};
</script>

<style lang="less" scoped>
/* 编辑区 */
.editor-bar {
  position: relative;
  border: 1px solid #eee;
  width: 810px;
}

/* 附件图标 */
.file-icon {
  position: absolute;
  top: 11px;
  right: 180px;
  width: 18px;
  height: 18px;
  z-index: 10000000;
  cursor: pointer;
  /* left: 1480px; */
}

/* 附件图标图片 */
.file-icon img {
  width: 100%;
  height: 100%;
  display: block;
}

/* 文本区 */
.editor-text-wrap {
  height: 200px;
  width: 810px;
  margin-top: -1px;
}

.editor-text {
  border: 1px solid #eee;
  height: 100%;

  /deep/ .w-e-text-container {
    .w-e-text {
      p {
        background-color: white;
      }
    }
  }
}

/* 文件区 */
.file-list {
  padding: 20px 0 0 20px;
  display: flex;
  border: 1px solid #eee;
  flex-wrap: wrap;
  margin: 0;
}

.file-item {
  margin: 0 20px 20px 0;
}

.imgBox {
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
  border: 1px solid #eee;
  flex-wrap: wrap;
  width: 810px;
  height: 120px;

  .el {
    margin-right: 20px;
    position: relative;

    i {
      position: absolute;
      top: 5px;
      right: 5px;
      z-index: 10000;
      color: white;
    }
  }
}
</style>
